<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 * ============================================================================
 * $Author: IT宇宙人 2015-08-10 $
 */ 
namespace Home\Controller;
use Think\Page;
use Think\Verify;
use Home\Logic\UsersLogic;
class IndexController extends BaseController {
    
 



    public function index(){


		$lang = L('_LANG_');
		$this->assign('navid', "home");
		$this->assign('wellcome', $lang);

		
        // 如果是手机跳转到 手机模块
       /* if(true == isMobile()){
            header("Location: ".U('Mobile/Index/index'));
        }*/
        
        $hot_goods = $hot_cate = $cateList = array();
        $sql = "select a.goods_name,a.goods_id,a.shop_price,a.market_price,a.cat_id,b.parent_id_path,b.name from __PREFIX__goods as a left join ";
        $sql .= " __PREFIX__goods_category as b on a.cat_id=b.id where a.is_hot=1 and a.is_on_sale=1 order by a.sort";//二级分类下热卖商品       
        $index_hot_goods = M()->query($sql);//首页热卖商品
		if($index_hot_goods){
			foreach($index_hot_goods as $val){
				$cat_path = explode('_', $val['parent_id_path']);
				$hot_goods[$cat_path[1]][] = $val;
			}
		}

        $hot_category = M('goods_category')->where("is_hot=1 and level=3 and is_show=1")->select();//热门三级分类
        foreach ($hot_category as $v){
        	$cat_path = explode('_', $v['parent_id_path']);
        	$hot_cate[$cat_path[1]][] = $v;
        }
        
        foreach ($this->cateTrre as $k=>$v){
            if($v['is_hot']==1){
        		$v['hot_goods'] = empty($hot_goods[$k]) ? '' : $hot_goods[$k];
        		$v['hot_cate'] = empty($hot_cate[$k]) ? '' : $hot_cate[$k];
        		$cateList[] = $v;
        	}
        }




        //footer 侧边栏 浏览记录
        $look_arr=cookie('look_arr');
        if($look_arr){
            $look_str='';
            foreach($look_arr AS $vv){
                if($vv){
                    $look_str?$look_str.=','.$vv:$look_str.=$vv;
                }
            }
            $look_where['goods_id']=array('in',$look_str);
            $look_where['is_on_sale']=1;
            $look_goods =M('goods')->where($look_where)->limit('20')->select();
            $this->assign('look_goods',$look_goods);
        }







        //首页头部
        $q='ESDH';
        $where['keywords'] =array('like','%'.$q.'%');
        $head_list = M('goods')->where($where)->order(" sort ASC")->limit(8)->select();
        //首页身体
        $q='CASD';
        $where['keywords'] =array('like','%'.$q.'%');
        $body_list = M('goods')->where($where)->order(" sort ASC")->limit(8)->select();
        $this->assign('head_list',$head_list);
        $this->assign('body_list',$body_list);


        
        $this->assign('cateList',$cateList); 
        $this->display();
    }


        public function ajax_set_exchange_rate(){

                session('exchange_rate_id',I('id'));
        }


    public function gather_email(){
        $email =I('email');
        $count =M('gather_email')->where(array('email'=>$email))->count();
        if($count){
            exit(json_encode(array('status'=>0,'msg'=>'Email has been submitted,Please do not repeat submit')));
        }else{
            $data['email']=$email;
            $data['addtime']=time();
            $data['status']=0;
            M('gather_email')->add($data);
            exit(json_encode(array('status'=>1,'msg'=>'Email has been submitted')));
        }
    }


    /**
     * 查询积分卡信息
     */
    public function get_scorecard(){
        $user_id =$_SESSION['user']['user_id'];
        $card = I('card');
        if(!$user_id)
            $this->error('Log in to check, please login!',U('Home/User/login'));
        $where['key']=$card;
        $card_info=M('scorecard')->where($where)->find();
        if(!$card_info){//积分卡不存在
            $this->error('This card is not a card that comes with my official product. You can check if the card number you entered is incorrect. If it is correct, you may buy counterfeit.');
        }elseif($card_info['status']==1){//积分卡被使用
            $this->error('The score of this card has been used. Thank you for your support for our products.');
        }elseif($card_info['status']==0){//积分卡未被使用

            //更新消费信息
            update_user_level($user_id,'',1000);
            //写入积分更新日志
            up_user_scorecard_log($user_id,1000,'购买商品获得');

            //更新积分卡信息
//            M('scorecard')->save(array('id'=>$card_info['id'],'status'=>1));
            $this->success('This card is the bonus card that comes with our genuine products, the points of this card have been added to your account');
        }

    }

    public function orderdetail(){
        $where['order_sn']=I('code');
        $order_info=M('order')->where($where)->find();
        if(!$order_info)
            $this->error('Order not longer exist',U('Index/index'));

        $f_address=M('user_address')->where(array('address_id'=>$order_info['f_address_id']))->find();
        $g_address=M('user_address')->where(array('address_id'=>$order_info['g_address_id']))->find();





            //获取订单商品
        $model = new UsersLogic();
        $data = $model->get_order_goods($order_info['order_id']);
        $order_info['goods_list'] = $data['result'];



        $this->assign('f_address',$f_address);
        $this->assign('g_address',$g_address);
        $this->assign('order_info',$order_info);
        $this->display();
    }

    public function joinus(){
        if(IS_POST){
            $data=I();
            $join_select=I('join_select');
            if($join_select){
                $sel_str='';
                foreach($join_select AS $v){
                    !empty($sel_str)?$sel_str.=','.$v:$sel_str.=$v;
                }
                $data['join_select']=$sel_str;
            }
            $data['add_time']=time();
            $data['user_id']=$_SESSION['user']['user_id'];
            $res=M('join')->add($data);
            if($res){
                //发送邮件通知管理员
                $config = tpCache('basic');
                $admin_email=$config['admin_email'];
//                $admin_email='459796567@qq.com';
                if($admin_email){
                    $admin_title='代理商申请提交通知';
                    $admin_content='有用户提交了代理商申请，请即时处理！详细信息如下(姓名：'.$data['first_name'].'/'.$data['last_name'].',邮箱：'.$data['email'].',电话：'.$data['tel'].',公司名：'.$data['company'].',职称：'.$data['job_title'].',地区：'.$data['state'].'),更多详细信息，请登录后台查看！';
                    send_email($admin_email,$admin_title,$admin_content);    //发送邮件通知
                }
                $this->success('add success');
            }else{
                $this->error('Add failed try again.');
            }
        }
        $this->display();
    }

    public function adultsonly(){
        $n_url=cookie('n_url');


        $this->assign('n_url',$n_url);
      

        $this->display();
    }


    public function yotpo(){


        $this->display();
    }


    public function designyourdreamgirl(){
        $this->display();
    }
 
	public function ajaxadultsonlyTop()
    {       
	   if($_COOKIE["18adultsonly"])
	   {
			//cookie('hidetopstatus','null',time() - 3600);
		   	unset($_COOKIE['18adultsonly']);
		   	cookie('18adultsonly','18adultsonly',60*60*24*365);
	   }
	   else
	   {
		   	cookie('18adultsonly','18adultsonly',60*60*24*365);    
	   }
	   
			$return_arr = array('status'=>1,'msg'=>'','result'=>''); // 返回结果状态  
        exit(json_encode($return_arr));
    }
	
	
    /**
     *  公告详情页
     */
    public function notice(){
        $this->display();
    }
    
	public function ajaxHideTop()
    {       
       // $ids = I("ids"); // 商品 ids        
       // $result = M("Cart")->where(" id in ($ids)")->delete(); // 删除id为5的用户数据
	   if($_COOKIE["hidetopstatus"]=="show")
	   {
			//cookie('hidetopstatus','null',time() - 3600);
		   	//unset($_COOKIE['hidetopstatus']);
			//cookie('hidetopstatus','asdkfjsadlfadsf',time() - 3600);
		   	cookie('hidetopstatus','hide',3600);
			$return_arr = array('status'=>2,'msg'=>'','result'=>''); // 返回结果状态     
	   }
	   else
	   {
			cookie('hidetopstatus','show',3600);
			$return_arr = array('status'=>1,'msg'=>'','result'=>''); // 返回结果状态       
	   }
        exit(json_encode($return_arr));
    }
	
    // 二维码
    public function qr_code(){        
        // 导入Vendor类库包 Library/Vendor/Zend/Server.class.php
        //http://www.tp-shop.cn/Home/Index/erweima/data/www.99soubao.com
         require_once 'ThinkPHP/Library/Vendor/phpqrcode/phpqrcode.php';
          //import('Vendor.phpqrcode.phpqrcode');
            error_reporting(E_ERROR);            
            $url = urldecode($_GET["data"]);
            \QRcode::png($url);          
    }
    
    // 验证码
    public function verify()
    {
        //验证码类型
        $type = I('get.type') ? I('get.type') : '';
        $fontSize = I('get.fontSize') ? I('get.fontSize') : '40';
        $length = I('get.length') ? I('get.length') : '4';
        $imageH = I('get.imageH') ? I('get.imageH') : '30';
        $imageW = I('get.imageW') ? I('get.imageW') : '80';
        
        $config = array(
            'fontSize' => $fontSize,
            'length' => $length,
            'imageH' => $imageH,
            'imagew' => $imageW,
            'useCurve' => false,
            'useNoise' => false,
        );
        $Verify = new Verify($config);
        $Verify->entry($type);        
    }
    
    // 促销活动页面
    public function promoteList()
    {                          
        $Model = new \Think\Model();
        $goodsList = $Model->query("select * from __PREFIX__goods as g inner join __PREFIX__flash_sale as f on g.goods_id = f.goods_id   where ".time()." > start_time  and ".time()." < end_time");                        
        $brandList = M('brand')->getField("id,name,logo");
        $this->assign('brandList',$brandList);
        $this->assign('goodsList',$goodsList);
        $this->display();
    }
    
    function truncate_tables (){
        $model = new \Think\Model(); // 实例化一个model对象 没有对应任何数据表
        $tables = $model->query("show tables");
        $table = array('tp_admin','tp_config','tp_region','tp_system_module','tp_admin_role','tp_system_menu');
        foreach($tables as $key => $val)
        {                                    
            if(!in_array($val['tables_in_tpshop'], $table))                             
                echo "truncate table ".$val['tables_in_tpshop'].' ; ';
                echo "<br/>";         
        }                
    }


    public function message(){


        $this->display();
    }



    public function add_message(){

//        echo 'illegal operation '; exit;
        $data=I();
        $data['status']=0;
        $data['add_time']=time();
        if($_SESSION['user']['user_id'])
            $data['user_id']=$_SESSION['user']['user_id'];

        if($_FILES['file']['tmp_name']){
                $dir=UPLOAD_PATH.'massages';
                if (!file_exists($dir)){
                   mkdir($dir,0777,true);
                   chmod($dir, 0777);
                }
                $upload = new \Think\Upload();// 实例化上传类
                $upload->maxSize   =     (1024*1024*3);// 设置附件上传大小 管理员10M  否则 2M
                $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath  =     $dir.'/'; // 设置附件上传根目录
                $upload->replace  =     true; // 存在同名文件是否是覆盖，默认为false
                // 上传文件
                $info   =   $upload->upload();
                $data['img']=$dir.'/'.$info['file']['savepath'].$info['file']['savename'];
            }
        $res=M('leave_message')->add($data);
        if($res){
            if($_SESSION['user']['user_id']){
                $user=M('users')->where(array('user_id'=>$_SESSION['user']['user_id']))->find();
                $admin_title='注册用户留言通知';
                $admin_content='注册用户：'.$user['nickname'].'(邮箱：'.$data['email'].'),于'.date('Y-m-d H:i:s').'添加了一条留言，留言内容"'.$data['content'].'"';
                if($data['img'])
                    $admin_content.=',留言附带附件，请登录管理后台查看该留言的详细信息。';
            }else{
                $admin_title='游客用户留言通知';
                $admin_content='游客：'.$data['name'].'(邮箱：'.$data['email'].'),于'.date('Y-m-d H:i:s').'添加了一条留言，留言内容"'.$data['content'].'"';
                if($data['img'])
                    $admin_content.=',留言附带附件，请登录管理后台查看该留言的详细信息。';
            }
            //发送邮件通知管理员
            $config = tpCache('basic');
            $admin_email=$config['admin_email'];//获取后台等级的管理员邮箱
//            $admin_email='459796567@qq.com';
            send_email($admin_email,$admin_title,$admin_content);    //发送邮件通知




            $this->success('add success');
        }else{
            $this->error('Add failed try again.');
        }
    }





}